<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Message, Modal } from '@arco-design/web-vue'
import { useMerchantStore } from '@/stores/merchant'
import {
  getMerchantDishes,
  getDishListByMerchantId,
  getDishByMerchantId,
  createDish,
  updateDish,
  deleteDish,
  updateDishStatus,
  updateDishRecommendedStatus,
  updateDishSpecialStatus,
  getDishCategoryByMerchantId,
  createDishCategory,
  updateDishCategory,
  deleteDishCategory,
  type Dish,
  type DishCategory,
  type CreateDishParams,
  type UpdateDishParams,
  type CreateDishCategoryParams
} from '@/api/dish'

const router = useRouter()
const merchantStore = useMerchantStore()
const loading = ref(false)
const tableLoading = ref(false)
const dishes = ref<Dish[]>([])
const categories = ref<DishCategory[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 菜品表单
const dishFormVisible = ref(false)
const dishFormLoading = ref(false)
const isEditMode = ref(false)
const currentDishId = ref<number | null>(null)
const dishForm = reactive<CreateDishParams>({
  name: '',
  price: 0,
  image: '',
  description: '',
  categoryId: 0,
  merchantId: 0,
  isSpecial: 0,
  specialPrice: 0,
  isRecommended: 0,
  status: 1
})

// 分类表单
const categoryFormVisible = ref(false)
const categoryFormLoading = ref(false)
const isEditCategoryMode = ref(false)
const currentCategoryId = ref<number | null>(null)
const categoryForm = reactive<CreateDishCategoryParams>({
  name: '',
  icon: '',
  sort: 1,
  merchantId: 0,
  status: 1
})

// 初始化数据
onMounted(async () => {
  loading.value = true
  try {
    // 如果store中没有商家信息，则获取
    if (!merchantStore.currentMerchant) {
      await merchantStore.fetchCurrentMerchant()
    }
    
    // 如果获取失败或仍然没有商家信息，跳转到登录页
    if (!merchantStore.currentMerchant) {
      throw new Error('获取商家信息失败')
    }
    
    // 设置商家ID
    dishForm.merchantId = merchantStore.currentMerchant.id
    categoryForm.merchantId = merchantStore.currentMerchant.id
    
    // 加载菜品分类
    await loadCategories()
    
    // 加载菜品数据
    await loadDishes()
    
  } catch (error) {
    console.error('初始化失败:', error)
    Message.error('初始化失败，请稍后再试')
    
    // 如果获取商家信息失败，可能是token无效，跳转到登录页
    router.push('/merchant/login')
  } finally {
    loading.value = false
  }
})

// 加载菜品数据
const loadDishes = async () => {
  if (!merchantStore.currentMerchant) {
    console.error('商家信息不存在，无法加载菜品')
    return
  }
  
  console.log('开始加载菜品数据，商家ID:', merchantStore.currentMerchant.id)
  tableLoading.value = true
  try {
    console.log('调用认证接口获取商家菜品列表')
    
    // 使用认证接口获取商家菜品列表
    const res = await getMerchantDishes()
    console.log('菜品列表接口返回结果:', res)
    
    if (res.code === 200 && res.data) {
      dishes.value = res.data
      pagination.total = res.data.length
      console.log('成功获取菜品列表:', dishes.value)
    } else {
      throw new Error(res.message || '获取菜品列表失败')
    }
  } catch (error) {
    console.error('加载菜品失败:', error)
    Message.error('加载菜品失败，请稍后再试')
  } finally {
    tableLoading.value = false
  }
}

// 加载菜品分类
const loadCategories = async () => {
  if (!merchantStore.currentMerchant) {
    console.error('商家信息不存在，无法加载分类')
    return
  }
  
  console.log('开始加载菜品分类，商家ID:', merchantStore.currentMerchant.id)
  try {
    const res = await getDishCategoryByMerchantId(merchantStore.currentMerchant.id)
    console.log('菜品分类接口返回结果:', res)
    
    if (res.code === 200 && res.data) {
      categories.value = res.data
      console.log('成功获取菜品分类:', categories.value)
    } else {
      throw new Error(res.message || '获取菜品分类失败')
    }
  } catch (error) {
    console.error('加载菜品分类失败:', error)
    Message.error('加载菜品分类失败，请稍后再试')
  }
}

// 分页变化
const onPageChange = (page: number) => {
  pagination.current = page
  // 客户端分页，不需要重新加载数据
}

// 每页条数变化
const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  // 客户端分页，不需要重新加载数据
}

// 打开添加菜品表单
const openAddDishForm = () => {
  isEditMode.value = false
  currentDishId.value = null
  resetDishForm()
  dishFormVisible.value = true
}

// 打开编辑菜品表单
const openEditDishForm = (dish: Dish) => {
  isEditMode.value = true
  currentDishId.value = dish.id
  
  // 填充表单
  dishForm.name = dish.name
  dishForm.price = dish.price
  dishForm.image = dish.image
  dishForm.description = dish.description
  dishForm.categoryId = dish.categoryId
  dishForm.isSpecial = dish.isSpecial
  dishForm.specialPrice = dish.specialPrice || 0
  dishForm.isRecommended = dish.isRecommended
  dishForm.status = dish.status
  
  dishFormVisible.value = true
}

// 重置菜品表单
const resetDishForm = () => {
  dishForm.name = ''
  dishForm.price = 0
  dishForm.image = ''
  dishForm.description = ''
  dishForm.categoryId = categories.value.length > 0 ? categories.value[0].id : 0
  dishForm.isSpecial = 0
  dishForm.specialPrice = 0
  dishForm.isRecommended = 0
  dishForm.status = 1
}

// 提交菜品表单
const submitDishForm = async () => {
  if (!merchantStore.currentMerchant) return
  
  // 表单验证
  if (!dishForm.name) {
    Message.error('请输入菜品名称')
    return
  }
  
  if (dishForm.price <= 0) {
    Message.error('请输入有效的菜品价格')
    return
  }
  
  if (!dishForm.categoryId) {
    Message.error('请选择菜品分类')
    return
  }
  
  dishFormLoading.value = true
  try {
    if (isEditMode.value && currentDishId.value) {
      // 编辑模式
      const updateData: UpdateDishParams = {
        name: dishForm.name,
        price: dishForm.price,
        image: dishForm.image,
        description: dishForm.description,
        categoryId: dishForm.categoryId,
        isSpecial: dishForm.isSpecial,
        specialPrice: dishForm.specialPrice,
        isRecommended: dishForm.isRecommended,
        status: dishForm.status
      }
      
      const res = await updateDish(currentDishId.value, updateData)
      if (res.code === 200) {
        Message.success('更新菜品成功')
        dishFormVisible.value = false
        loadDishes()
      } else {
        throw new Error(res.message || '更新菜品失败')
      }
    } else {
      // 添加模式
      const res = await createDish({
        ...dishForm,
        merchantId: merchantStore.currentMerchant.id
      })
      
      if (res.code === 200) {
        Message.success('添加菜品成功')
        dishFormVisible.value = false
        loadDishes()
      } else {
        throw new Error(res.message || '添加菜品失败')
      }
    }
  } catch (error) {
    console.error('提交菜品表单失败:', error)
    Message.error('操作失败，请稍后再试')
  } finally {
    dishFormLoading.value = false
  }
}

// 删除菜品
const confirmDeleteDish = (dish: Dish) => {
  Modal.warning({
    title: '确认删除',
    content: `确定要删除菜品 "${dish.name}" 吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        const res = await deleteDish(dish.id)
        if (res.code === 200) {
          Message.success('删除菜品成功')
          loadDishes()
        } else {
          throw new Error(res.message || '删除菜品失败')
        }
      } catch (error) {
        console.error('删除菜品失败:', error)
        Message.error('删除菜品失败，请稍后再试')
      }
    }
  })
}

// 更新菜品状态
const toggleDishStatus = async (dish: Dish) => {
  try {
    const newStatus = dish.status === 1 ? 0 : 1
    const res = await updateDishStatus(dish.id, newStatus)
    if (res.code === 200) {
      Message.success(`${newStatus === 1 ? '上架' : '下架'}菜品成功`)
      // 直接更新本地数据，而不是重新加载
      dish.status = newStatus
    } else {
      throw new Error(res.message || '更新菜品状态失败')
    }
  } catch (error) {
    console.error('更新菜品状态失败:', error)
    Message.error('更新菜品状态失败，请稍后再试')
  }
}

// 更新菜品推荐状态
const toggleRecommendedStatus = async (dish: Dish) => {
  try {
    const newStatus = dish.isRecommended === 1 ? 0 : 1
    const res = await updateDishRecommendedStatus(dish.id, newStatus)
    if (res.code === 200) {
      Message.success(`${newStatus === 1 ? '设为' : '取消'}推荐菜品成功`)
      dish.isRecommended = newStatus
    } else {
      throw new Error(res.message || '更新推荐状态失败')
    }
  } catch (error) {
    console.error('更新推荐状态失败:', error)
    Message.error('更新推荐状态失败，请稍后再试')
  }
}

// 更新菜品特价状态
const toggleSpecialStatus = async (dish: Dish, specialPrice?: number) => {
  try {
    const newStatus = dish.isSpecial === 1 ? 0 : 1
    const price = specialPrice || dish.specialPrice || Math.floor(dish.price * 0.8)
    
    const res = await updateDishSpecialStatus(dish.id, newStatus, price)
    if (res.code === 200) {
      Message.success(`${newStatus === 1 ? '设置' : '取消'}特价成功`)
      dish.isSpecial = newStatus
      dish.specialPrice = price
    } else {
      throw new Error(res.message || '更新特价状态失败')
    }
  } catch (error) {
    console.error('更新特价状态失败:', error)
    Message.error('更新特价状态失败，请稍后再试')
  }
}

// 打开添加分类表单
const openAddCategoryForm = () => {
  isEditCategoryMode.value = false
  currentCategoryId.value = null
  resetCategoryForm()
  categoryFormVisible.value = true
}

// 打开编辑分类表单
const openEditCategoryForm = (category: DishCategory) => {
  isEditCategoryMode.value = true
  currentCategoryId.value = category.id
  
  // 填充表单
  categoryForm.name = category.name
  categoryForm.icon = category.icon
  categoryForm.sort = category.sort
  categoryForm.status = category.status
  
  categoryFormVisible.value = true
}

// 重置分类表单
const resetCategoryForm = () => {
  categoryForm.name = ''
  categoryForm.icon = ''
  categoryForm.sort = 1
  categoryForm.status = 1
}

// 提交分类表单
const submitCategoryForm = async () => {
  if (!merchantStore.currentMerchant) return
  
  // 表单验证
  if (!categoryForm.name) {
    Message.error('请输入分类名称')
    return
  }
  
  categoryFormLoading.value = true
  try {
    if (isEditCategoryMode.value && currentCategoryId.value) {
      // 编辑模式
      const updateData = {
        name: categoryForm.name,
        icon: categoryForm.icon,
        sort: categoryForm.sort,
        status: categoryForm.status,
        merchantId: merchantStore.currentMerchant.id // 添加merchantId字段
      }
      
      const res = await updateDishCategory(currentCategoryId.value, updateData)
      if (res.code === 200) {
        Message.success('更新分类成功')
        categoryFormVisible.value = false
        loadCategories()
      } else {
        throw new Error(res.message || '更新分类失败')
      }
    } else {
      // 添加模式
      const res = await createDishCategory({
        ...categoryForm,
        merchantId: merchantStore.currentMerchant.id
      })
      
      if (res.code === 200) {
        Message.success('添加分类成功')
        categoryFormVisible.value = false
        loadCategories()
      } else {
        throw new Error(res.message || '添加分类失败')
      }
    }
  } catch (error) {
    console.error('提交分类表单失败:', error)
    Message.error('操作失败，请稍后再试')
  } finally {
    categoryFormLoading.value = false
  }
}

// 删除分类
const confirmDeleteCategory = (category: DishCategory) => {
  Modal.warning({
    title: '确认删除',
    content: `确定要删除分类 "${category.name}" 吗？删除分类可能会影响相关菜品。`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        const res = await deleteDishCategory(category.id)
        if (res.code === 200) {
          Message.success('删除分类成功')
          loadCategories()
        } else {
          throw new Error(res.message || '删除分类失败')
        }
      } catch (error) {
        console.error('删除分类失败:', error)
        Message.error('删除分类失败，请稍后再试')
      }
    }
  })
}

// 获取分类名称
const getCategoryName = (categoryId: number) => {
  const category = categories.value.find(c => c.id === categoryId)
  return category ? category.name : '未知分类'
}

// 返回商家管理中心
const goToDashboard = () => {
  router.push('/merchant/dashboard')
}
</script>

<template>
  <div class="merchant-dishes-container">
    <a-spin :loading="loading" tip="加载中...">
      <!-- 标题栏 -->
      <div class="dishes-header">
        <a-button shape="circle" @click="goToDashboard">
          <template #icon><icon-left /></template>
        </a-button>
        <h2>菜品管理</h2>
        <div></div>
      </div>

      <div class="dishes-content">
        <!-- 操作按钮 -->
        <div class="dishes-actions">
          <a-space>
            <a-button type="primary" @click="openAddDishForm">
              <template #icon><icon-plus /></template>
              添加菜品
            </a-button>
            <a-button @click="openAddCategoryForm">
              <template #icon><icon-folder-add /></template>
              添加分类
            </a-button>
            <a-button @click="loadDishes">
              <template #icon><icon-refresh /></template>
              刷新
            </a-button>
          </a-space>
        </div>

        <!-- 菜品分类管理 -->
        <div class="categories-section">
          <h3>菜品分类</h3>
          <a-table
            :data="categories"
            :pagination="false"
            :bordered="false"
            stripe
            row-key="id"
          >
            <template #columns>
              <a-table-column title="分类名称" data-index="name" />
              <a-table-column title="排序" data-index="sort" />
              <a-table-column title="状态" data-index="status">
                <template #cell="{ record }">
                  <a-tag :color="record.status === 1 ? 'green' : 'red'">
                    {{ record.status === 1 ? '启用' : '禁用' }}
                  </a-tag>
                </template>
              </a-table-column>
              <a-table-column title="操作">
                <template #cell="{ record }">
                  <a-space>
                    <a-button type="text" size="small" @click="openEditCategoryForm(record)">
                      编辑
                    </a-button>
                    <a-button type="text" size="small" status="danger" @click="confirmDeleteCategory(record)">
                      删除
                    </a-button>
                  </a-space>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>

        <!-- 菜品列表 -->
        <div class="dishes-section">
          <h3>菜品列表</h3>
          <a-table
            :data="dishes"
            :loading="tableLoading"
            :pagination="{
              total: pagination.total,
              current: pagination.current,
              pageSize: pagination.pageSize,
              showTotal: true,
              showPageSize: true
            }"
            @page-change="onPageChange"
            @page-size-change="onPageSizeChange"
            :bordered="false"
            stripe
            row-key="id"
          >
            <template #columns>
              <a-table-column title="菜品名称" data-index="name" />
              <a-table-column title="图片" data-index="image">
                <template #cell="{ record }">
                  <a-image
                    v-if="record.image"
                    :src="record.image"
                    :preview-visible="false"
                    width="60"
                    height="60"
                    fit="cover"
                  />
                  <span v-else>暂无图片</span>
                </template>
              </a-table-column>
              <a-table-column title="价格" data-index="price">
                <template #cell="{ record }">
                  <div>
                    <span :class="{ 'price-original': record.isSpecial === 1 }">¥{{ record.price }}</span>
                    <span v-if="record.isSpecial === 1" class="price-special">¥{{ record.specialPrice }}</span>
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="分类" data-index="categoryId">
                <template #cell="{ record }">
                  {{ getCategoryName(record.categoryId) }}
                </template>
              </a-table-column>
              <a-table-column title="状态" data-index="status">
                <template #cell="{ record }">
                  <a-space>
                    <a-tag :color="record.status === 1 ? 'green' : 'red'">
                      {{ record.status === 1 ? '上架' : '下架' }}
                    </a-tag>
                    <a-tag v-if="record.isRecommended === 1" color="orange">推荐</a-tag>
                    <a-tag v-if="record.isSpecial === 1" color="purple">特价</a-tag>
                  </a-space>
                </template>
              </a-table-column>
              <a-table-column title="操作" fixed="right" :width="240">
                <template #cell="{ record }">
                  <a-space>
                    <a-button type="text" size="small" @click="openEditDishForm(record)">
                      编辑
                    </a-button>
                    <a-button 
                      type="text" 
                      size="small" 
                      :status="record.status === 1 ? 'danger' : 'success'"
                      @click="toggleDishStatus(record)"
                    >
                      {{ record.status === 1 ? '下架' : '上架' }}
                    </a-button>
                    <a-button 
                      type="text" 
                      size="small" 
                      :status="record.isRecommended === 1 ? 'danger' : 'success'"
                      @click="toggleRecommendedStatus(record)"
                    >
                      {{ record.isRecommended === 1 ? '取消推荐' : '设为推荐' }}
                    </a-button>
                    <a-button 
                      type="text" 
                      size="small" 
                      :status="record.isSpecial === 1 ? 'danger' : 'warning'"
                      @click="toggleSpecialStatus(record)"
                    >
                      {{ record.isSpecial === 1 ? '取消特价' : '设为特价' }}
                    </a-button>
                    <a-button type="text" size="small" status="danger" @click="confirmDeleteDish(record)">
                      删除
                    </a-button>
                  </a-space>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>
      </div>
    </a-spin>

    <!-- 添加/编辑菜品表单 -->
    <a-modal
      v-model:visible="dishFormVisible"
      :title="isEditMode ? '编辑菜品' : '添加菜品'"
      @cancel="dishFormVisible = false"
      @before-ok="submitDishForm"
      :ok-loading="dishFormLoading"
    >
      <a-form :model="dishForm" layout="vertical">
        <a-form-item field="name" label="菜品名称">
          <a-input v-model="dishForm.name" placeholder="请输入菜品名称" />
        </a-form-item>
        <a-form-item field="price" label="菜品价格">
          <a-input-number v-model="dishForm.price" placeholder="请输入菜品价格" mode="button" min="0" step="0.01" />
        </a-form-item>
        <a-form-item field="categoryId" label="所属分类">
          <a-select v-model="dishForm.categoryId" placeholder="请选择分类">
            <a-option 
              v-for="category in categories" 
              :key="category.id" 
              :value="category.id"
              :disabled="category.status === 0"
            >
              {{ category.name }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="image" label="菜品图片">
          <a-input v-model="dishForm.image" placeholder="请输入菜品图片URL" />
        </a-form-item>
        <a-form-item field="description" label="菜品描述">
          <a-textarea v-model="dishForm.description" placeholder="请输入菜品描述" />
        </a-form-item>
        <a-form-item field="isSpecial" label="特价设置">
          <a-space>
            <a-switch v-model="dishForm.isSpecial" :checked-value="1" :unchecked-value="0" />
            <span>{{ dishForm.isSpecial === 1 ? '特价' : '非特价' }}</span>
          </a-space>
        </a-form-item>
        <a-form-item field="specialPrice" label="特价价格" v-if="dishForm.isSpecial === 1">
          <a-input-number v-model="dishForm.specialPrice" placeholder="请输入特价价格" mode="button" min="0" step="0.01" />
        </a-form-item>
        <a-form-item field="isRecommended" label="是否推荐">
          <a-space>
            <a-switch v-model="dishForm.isRecommended" :checked-value="1" :unchecked-value="0" />
            <span>{{ dishForm.isRecommended === 1 ? '推荐' : '不推荐' }}</span>
          </a-space>
        </a-form-item>
        <a-form-item field="status" label="菜品状态">
          <a-space>
            <a-switch v-model="dishForm.status" :checked-value="1" :unchecked-value="0" />
            <span>{{ dishForm.status === 1 ? '上架' : '下架' }}</span>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 添加/编辑分类表单 -->
    <a-modal
      v-model:visible="categoryFormVisible"
      :title="isEditCategoryMode ? '编辑分类' : '添加分类'"
      @cancel="categoryFormVisible = false"
      @before-ok="submitCategoryForm"
      :ok-loading="categoryFormLoading"
    >
      <a-form :model="categoryForm" layout="vertical">
        <a-form-item field="name" label="分类名称">
          <a-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </a-form-item>
        <a-form-item field="icon" label="分类图标">
          <a-input v-model="categoryForm.icon" placeholder="请输入分类图标URL" />
        </a-form-item>
        <a-form-item field="sort" label="排序">
          <a-input-number v-model="categoryForm.sort" placeholder="请输入排序值" mode="button" min="1" />
        </a-form-item>
        <a-form-item field="status" label="分类状态">
          <a-space>
            <a-switch v-model="categoryForm.status" :checked-value="1" :unchecked-value="0" />
            <span>{{ categoryForm.status === 1 ? '启用' : '禁用' }}</span>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.merchant-dishes-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.dishes-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
}

.dishes-header h2 {
  margin: 0;
  font-size: 24px;
  color: var(--color-text-1);
}

.dishes-content {
  background-color: var(--color-bg-2);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  padding: 24px;
}

.dishes-actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.categories-section {
  margin-bottom: 30px;
}

.categories-section h3,
.dishes-section h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 18px;
  color: var(--color-text-1);
}

.price-original {
  text-decoration: line-through;
  color: var(--color-text-3);
  margin-right: 8px;
}

.price-special {
  color: var(--color-danger);
  font-weight: bold;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .merchant-dishes-container {
    padding: 16px;
  }
  
  .dishes-content {
    padding: 16px;
  }
}
</style> 